package com.sun.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.dao.OrdersMapper;
import com.sun.dao.RoomMapper;
import com.sun.dao.RoomTypeMapper;
import com.sun.pojo.Orders;
import com.sun.pojo.Room;
import com.sun.pojo.RoomType;
import com.sun.service.OrdersService;
import com.sun.utils.DataGridViewResult;
import com.sun.utils.UUIDutiles;
import com.sun.vo.OrdersVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private RoomTypeMapper roomTypeMapper;

    @Transactional(rollbackFor = RuntimeException.class)
    public int addOrders(Orders orders) {
        orders.setOrdersno(UUIDutiles.getUuid().substring(0, 18));
        orders.setStatus(1);
        orders.setReservedate(new Date());
        int ordersAddRes = ordersMapper.addOrders(orders);
        if (ordersAddRes > 0) {
            // 房间状态改变为已预订(1)
            Room room = new Room();
            room.setId(orders.getRoomid());
            room.setStatus(1);
            int roomUpdateRes = roomMapper.updateRoom(room);

            // 改变房型数据：可用房间-1 预定房间+1
            RoomType roomType = roomTypeMapper.findById(orders.getRoomtypeid());
            roomType.setAvilablenum(roomType.getAvilablenum() - 1);
            roomType.setReservednum(roomType.getReservednum() + 1);
            int roomTypeUpdateRes = roomTypeMapper.updateRoomType(roomType);
        }
        return ordersAddRes;
    }

    public DataGridViewResult list(OrdersVo ordersVo) {
        PageHelper.startPage(ordersVo.getPage(),ordersVo.getLimit());
        List<Orders> list = ordersMapper.list(ordersVo);
        PageInfo<Orders> pageInfo = new PageInfo<Orders>(list);
        return new DataGridViewResult(pageInfo.getTotal(),pageInfo.getList());
    }


    @Transactional(rollbackFor = RuntimeException.class)
    public int confirmOrders(int id) {
        Orders orders=new Orders();
        orders.setId(id);
        orders.setStatus(2);
        return ordersMapper.updateOrders(orders);
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public int batchConfirmOrders(String ids) {
        String[] idList = ids.split(",");

        int count=0;
        Orders orders=new Orders();
        for (String id : idList) {
            orders.setId(Integer.valueOf(id));
            orders.setStatus(2);
            int i=ordersMapper.updateOrders(orders);
            if(i>0){
                count++;
            }
        }
        if(count==idList.length){
            return 1;
        }
        return 0;
    }
}
